<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-if="checkPermission(permissionRoles.email_pass)" v-waves :loading="actLoading" :disabled="disabled" type="success" icon="el-icon-s-check" class="filter-item" @click="pass()">批量审核</el-button>
      <el-button v-if="checkPermission(permissionRoles.email_del)" class="filter-item" type="danger" icon="el-icon-close" @click="handleDelete">批量删除</el-button>
      <el-button v-if="checkPermission(permissionRoles.email_personal)" class="filter-item" type="primary" icon="el-icon-user" @click="personalCreate">个人邮件</el-button>
      <el-button v-if="checkPermission(permissionRoles.email_public)" class="filter-item" type="warning" icon="el-icon-plus" @click="publicCreate">公共邮件</el-button>
    </div>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      stripe
      highlight-current-row
      class="table-content"
      height="670"
      :cell-class-name="cellClassNameFn"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column label="标题" align="center" width="150px" prop="display_title"></el-table-column>
      <el-table-column label="内容" align="center" width="200px" prop="display_content"></el-table-column>
      <el-table-column label="附件" align="center" width="400px" prop="items_str"></el-table-column>
      <el-table-column label="类型" class-name="status-col" width="85" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.type === 1" type="primary">个人邮件</el-tag>
          <el-tag v-else type="warning">公共邮件</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="收件人" width="150px" align="center" prop="actorid"></el-table-column>
      <el-table-column label="添加时间" width="140px" align="center" prop="create_dt"></el-table-column>
      <el-table-column label="审核时间" width="140px" align="center" prop="send_time"></el-table-column>
      <el-table-column label="发送人" width="70px" align="center" prop="sender"></el-table-column>
      <el-table-column label="审核人" width="70px" align="center" prop="reviewer"></el-table-column>
      <el-table-column label="状态" class-name="status-col" align="center" width="70px">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">{{ row.status | statusTextFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="120px">
        <template slot-scope="{row}">
          <el-button v-if="checkPermission(permissionRoles.email_pass) && row.status == 0" type="text" size="small" title="审核" @click="pass(row)">审核</el-button>
          <el-button v-if="checkPermission(permissionRoles.email_edit) && row.status == 0" type="text" size="small" title="编辑" @click="handleEdit(row)">修改</el-button>
          <el-button v-if="checkPermission(permissionRoles.email_del) && row.status == 0" type="text" size="small" title="删除" @click="handleDelete(row)">删除</el-button>
          <el-button v-if="row.status == 1" type="text" size="small" title="查看" @click="viewDetail(row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisiblePersonal" title="个人邮件" :close-on-click-modal="false">
      <el-form ref="personalForm" :model="personalForm" :rules="prules" label-width="100px" label-position="left">
        <el-form-item label="服务器" prop="sid">
          <el-select v-model="personalForm.sid" class="defaut-input" filterable clearable>
            <el-option
              v-for="(item, index) in servers"
              :key="index"
              :label="item.name + '(' + item.sid + ')'"
              :value="item.sid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色ID" prop="actorid">
          <el-input v-model="personalForm.actorid" type="textarea" :autosize="{ minRows: 5, maxRows: 8}" />
        </el-form-item>
        <el-form-item label="邮件标题" prop="title">
          <el-input v-model="personalForm.title" class="defaut-input" placeholder="填写邮件标题" />
        </el-form-item>
        <el-form-item label="邮件内容" prop="content">
          <el-input v-model="personalForm.content" type="textarea" :autosize="{ minRows: 5, maxRows: 8}" />
        </el-form-item>
        <el-form-item label="是否强制已读" prop="is_read">
          <el-radio v-model="personalForm.is_read" label="1">是</el-radio>
          <el-radio v-model="personalForm.is_read" label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="发送人" prop="sender">
          <el-input v-model="personalForm.sender" class="defaut-input" placeholder="填写发送人" />
        </el-form-item>
        <el-form-item label="附件内容">
          <el-row>
            <el-col :md="3"><el-button type="primary" class="add" icon="el-icon-plus" @click="productAdd">新增</el-button></el-col>
          </el-row>
          <el-row
            v-for="(item, index) in personalForm.items"
            :key="index"
            class="mt-5"
            :gutter="12"
          >
            <el-col :md="6">
              <el-select v-model="item.id" clearable filterable placeholder="请选择物品">
                <el-option
                  v-for="p in products"
                  :key="p.id"
                  :label="p.desc"
                  :value="p.id"
                />
              </el-select>
            </el-col>
            <el-col :md="8"><el-input v-model="item.num" placeholder="数量" /></el-col>
            <el-col :md="4"><el-button type="danger" icon="el-icon-delete" @click.prevent="remove(item)" /></el-col>
          </el-row>
        </el-form-item>

      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisiblePersonal=false">取消</el-button>
        <el-button type="primary" :disabled="isDisabled" @click="sendPersonalMail()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisiblePublic" title="公共邮件" :close-on-click-modal="false">
      <el-form ref="publicForm" :model="publicForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="邮件标题" prop="title">
          <el-input v-model="publicForm.title" class="defaut-input" placeholder="填写邮件标题" />
        </el-form-item>
        <el-form-item label="邮件内容" prop="content">
          <el-input v-model="publicForm.content" type="textarea" :autosize="{ minRows: 5, maxRows: 8}" />
        </el-form-item>
        <el-form-item label="发送条件">
          <el-input v-model="publicForm.level" prop="level" class="defaut-input" placeholder="等级">
            <template slot="prepend">等级</template>
          </el-input>
          <el-input v-model="publicForm.amount" prop="amount" class="defaut-input" placeholder="充值金额">
            <template slot="prepend">充值金额</template>
          </el-input>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-form-item>
            <el-date-picker
              v-model="publicForm.start_dt"
              type="datetime"
              style="width: 27%"
            /> -
            <el-date-picker
              v-model="publicForm.end_dt"
              type="datetime"
              style="width: 27%"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item label="是否强制已读" prop="is_read">
          <el-radio v-model="publicForm.is_read" label="1">是</el-radio>
          <el-radio v-model="publicForm.is_read" label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="发送人" prop="sender">
          <el-input v-model="publicForm.sender" class="defaut-input" placeholder="填写发送人" />
        </el-form-item>
        <el-form-item label="附件内容">
          <el-row>
            <el-col :md="3"><el-button type="primary" class="add" icon="el-icon-plus" @click="productpubAdd">新增</el-button></el-col>
          </el-row>
          <el-row
            v-for="(item, index) in publicForm.items"
            :key="index"
            class="mt-5"
            :gutter="12"
          >
            <el-col :md="6">
              <el-select v-model="item.id" clearable filterable placeholder="请选择物品">
                <el-option
                  v-for="p in products"
                  :key="p.id"
                  :label="p.desc"
                  :value="p.id"
                />
              </el-select>
            </el-col>
            <el-col :md="8"><el-input v-model="item.num" placeholder="数量" /></el-col>
            <el-col :md="4"><el-button type="danger" icon="el-icon-delete" @click.prevent="removepub(item)" /></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="发行渠道" prop="cpid">
          <el-select v-model="publicForm.cpid" multiple class="defaut-input" clearable>
            <el-option
              v-for="item in cpList"
              :key="item.cpid"
              :label="item.cpname"
              :value="item.cpid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务器选择">
          <el-checkbox v-model="allServerChecked" @change="checkAllServer">显示全服</el-checkbox>
        </el-form-item>
        <div class="server-box">
          <ul class="menu-sub">
            <li
              v-for="(sgit,index) in serverGroups"
              :key="index"
            >
              <el-checkbox
                v-model="sgit.flag"
                :indeterminate="itemIndeterminate(sgit)"
                @change="(val) => handleCheckAll(val, sgit)"
              >{{ sgit.sgname }}</el-checkbox>
              <el-checkbox-group
                v-model="selectedData"
                style="padding-left: 30px;"
                @change="handleChanges(sgit)"
              >
                <el-checkbox
                  v-for="sgits in sgit.children"
                  :key="sgits.sid"
                  :label="sgits.sid"
                >{{ sgits.name }}</el-checkbox>
              </el-checkbox-group>
            </li>
          </ul>
        </div>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisiblePublic=false">取消</el-button>
        <el-button type="primary" :disabled="isDisabled" @click="sendPublicMail()">确定</el-button>
      </div>
    </el-dialog>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import { getEmailList, sendPersonalEmail, sendPublicEmail, approved, deleteEmail } from '@/api/gm'
import { getServerList, getServerListGroup, getChannelPackageList } from '@/api/ops'
import { getItemConfig } from '@/api/config'
import { deepClone } from '@/utils'
import waves from '@/directive/waves' // 实现点击波浪纹
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const personItem = {
  id: '',
  sid: '',
  actorid: '',
  title: '',
  content: '',
  sender: '系统',
  is_read: '0',
  items: [{
    id: '',
    num: ''
  }]
}
const publicItem = {
  id: '',
  sids: [],
  cpid: [],
  title: '',
  content: '',
  sender: '系统',
  level: '',
  amount: '',
  start_dt: '',
  end_dt: '',
  is_read: '0',
  items: [{
    id: '',
    num: ''
  }]
}

export default {
  name: 'EmailList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'primary',
        1: 'success'
      }
      return statusMap[status]
    },
    statusTextFilter(status) {
      const statusTextMap = {
        0: '待审核',
        1: '已审核'
      }
      return statusTextMap[status]
    }
  },
  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      disabled: false,
      dialogVisiblePersonal: false,
      dialogVisiblePublic: false,
      downloadLoading: false,
      multipleSelection: [],
      allServerChecked: false,
      isDisabled: false,
      selectedData: [],
      tableKey: 0,
      list: [],
      servers: [],
      cpList: [],
      serverGroups: [],
      products: [],
      total: 0,
      listLoading: true,
      actLoading: false,
      personalForm: Object.assign({}, personItem),
      publicForm: Object.assign({}, publicItem),
      listQuery: {
        page: 1,
        limit: 200,
        type: 0,
        sort: '+id'
      },
      rules: {
        title: [{ required: true, message: '标题不能为空！', trigger: 'blur' }]
      },
      prules: {
        sid: [{ required: true, message: '请选择服务器！', trigger: 'blur' }],
        actorid: [{ required: true, message: '角色ID不能为空', trigger: 'blur' }],
        title: [{ required: true, message: '标题不能为空！', trigger: 'blur' }]
      }
    }
  },
  mounted() {
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    async getList() {
      const query = this.listQuery
      this.listLoading = true
      const res = await getEmailList(query)
      this.listLoading = false
      this.list = res.data.items
      this.total = res.data.total
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })
    },
    cellClassNameFn(row) {
      if (row.columnIndex === 0 && row.row.status === 1) {
        return 'table-column-hidden'
      }
    },
    async getServerList() {
      const res = await getServerList()
      this.servers = res.data.items
    },
    async getCpList() {
      const res = await getChannelPackageList()
      this.cpList = res.data.items
    },
    async getItemConfig() {
      const res = await getItemConfig()
      this.products = res.data.items
    },
    async serverListGroup(val) {
      getServerListGroup({ all: val }).then(res => {
        this.serverGroups = res.data
      })
    },

    handleFilter(query) {
      this.getList()
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.table.toggleRowSelection(row)
        })
      } else {
        this.$refs.table.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 添加个人邮件
    personalCreate() {
      this.isDisabled = false
      this.personalForm = Object.assign({}, personItem)
      this.dialogVisiblePersonal = true
      this.getServerList()
      this.getItemConfig()
      this.$nextTick(() => {
        this.$refs['personalForm'].clearValidate()
      })
    },

    // 添加公共邮件
    publicCreate() {
      this.selectedData = []
      this.isDisabled = false
      this.publicForm = Object.assign({}, publicItem)
      this.dialogVisiblePublic = true
      this.serverListGroup(false)
      this.getItemConfig()
      this.getCpList()
      this.$nextTick(() => {
        this.$refs['publicForm'].clearValidate()
      })
    },
    productAdd(row) {
      if (this.personalForm.items.length === 6) {
        return
      }
      this.personalForm.items.push({
        id: '',
        num: ''
      })
    },
    remove(row) {
      var index = personItem.items.indexOf(row)
      if (index !== -1) {
        personItem.items.splice(index, 1)
      }
    },
    productpubAdd(row) {
      if (this.publicForm.items.length === 6) {
        return
      }
      this.publicForm.items.push({
        id: '',
        num: ''
      })
    },
    removepub(row) {
      var index = this.publicForm.items.indexOf(row)
      if (index !== -1) {
        this.publicForm.items.splice(index, 1)
      }
    },
    sendPersonalMail() {
      this.$refs.personalForm.validate(valid => {
        if (valid) {
          this.loading = true
          sendPersonalEmail(this.personalForm).then(response => {
            this.loading = false
            this.$message.success('发送成功')
            this.dialogVisiblePersonal = false
            this.getList()
          }).catch(err => {
            this.loading = false
            console.error(err)
          })
        } else {
          return false
        }
      })
    },
    sendPublicMail() {
      if (this.selectedData.length <= 0) {
        this.$message.error('请选择服务器')
        return false
      }
      this.$refs.publicForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.publicForm.sids = this.selectedData
          if (this.publicForm.start_dt || this.publicForm.end_dt) {
            // 必须两个都填
            if (this.publicForm.start_dt === '' || this.publicForm.end_dt === '') {
              this.$message.error('开始、结束时间要么都不填，要么都填')
              return false
            }

            if (new Date(this.publicForm.start_dt) >= new Date(this.publicForm.end_dt)) {
              this.$message.error('结束时间必须大于开始时间')
              return false
            }
          }

          sendPublicEmail(this.publicForm).then(response => {
            this.loading = false
            this.$message.success('发送成功')
            this.dialogVisiblePublic = false
            this.getList()
          }).catch(err => {
            this.loading = false
            console.error(err)
          })
        } else {
          return false
        }
      })
    },
    toArray(data) {
      if (data === undefined || data === null) return []
      if (Array.isArray(data)) return data
      return [String(data)]
    },
    // 全选
    handleCheckAll(val, item) {
      // 过滤掉没有选中的数据，item.child中不包含v时返回-1
      const next = item.children.map(item => item.sid)
      const filterArr = this.selectedData.filter(
        (v) => next.indexOf(v) === -1
      )
      this.selectedData = val ? filterArr.concat(next) : filterArr
    },
    itemIndeterminate(item) {
      const infoLists = item.children.map(ite => ite.sid)
      console.log(infoLists)
      const selectedData = this.toArray(this.selectedData)
      // const selectedData = this.selectedData
      return (
        infoLists.some((v) => selectedData.indexOf(v) > -1) &&
        !infoLists.every((v) => selectedData.indexOf(v) > -1)
      )
    },
    // 勾选变化方法
    handleChanges(val) {
      const infoLists = val.children.map(ite => ite.sid)
      infoLists.every((v) => {
        if (this.selectedData.indexOf(v) > -1) {
          val.flag = true
        } else {
          val.flag = false
        }
      })
    },
    checkAllServer() {
      this.serverListGroup(this.allServerChecked)
    },

    // 邮件审批操作
    async pass(row) {
      if (this.multipleSelection.length <= 0 && typeof row === 'undefined') {
        this.$message.error('请至少选择一条未审核的记录')
        return false
      }

      this.$confirm('你确定审核吗?', '高风险操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.disabled = true
        const d = this.multipleSelection
        if (row) {
          d.push(row)
        }
        approved(d).then(response => {
          this.disabled = false
          this.multipleSelection = []
          if (response.status === true) {
            this.$message.success('操作成功!')
            this.getList()
          } else {
            this.$message.error('操作失败!')
          }
        })
      }).catch(err => {
        this.disabled = false
        console.error(err)
      })
    },

    // 邮件删除操作
    async handleDelete(row) {
      if (this.multipleSelection.length <= 0 && typeof row === 'undefined') {
        this.$message.error('请至少选择一条记录')
        return false
      }

      this.$confirm('你确定要删除吗?', '高风险操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(async() => {
        const d = this.multipleSelection
        if (row) {
          d.push(row)
        }
        deleteEmail(d).then(response => {
          this.multipleSelection = []
          if (response.status === true) {
            this.$message.success('操作成功!')
            this.getList()
          } else {
            this.$message.error('操作失败!')
          }
        })
      }).catch(err => {
        console.error(err)
      })
    },
    async handleEdit(row) {
      this.isDisabled = false
      this.editView(row)
    },
    viewDetail(row) {
      this.editView(row)
      this.isDisabled = true
    },
    editView(row) {
      if (row.items === null) row.items = ''

      if (Array.isArray(row.items) === false) {
        if (row.items === '') {
          row.items = [{ id: '', num: '' }]
        } else {
          const items = row.items.split(',')
          const a = []
          for (let i = 0; i < items.length; i++) {
            const o = { id: '', num: '' }
            const e = items[i].split('*')
            o.id = parseInt(e[0])
            o.num = parseInt(e[1])
            a[i] = o
          }
          row.items = a
        }
      }
      this.selectedData = row.sid
      if (row.title.substring(row.title.length - 3, row.title.length) === '...') {
        row.title = row.title.substring(0, row.title.length - 3)
      }
      if (row.content.substring(row.content.length - 3, row.content.length) === '...') {
        row.content = row.content.substring(0, row.content.length - 3)
      }

      this.getItemConfig()
      this.getCpList()
      if (row.type === 1) {
        this.getServerList()
        this.dialogVisiblePersonal = true
        this.personalForm = deepClone(row)
        this.$nextTick(() => {
          this.$refs['personalForm'].clearValidate()
        })
      } else {
        this.serverListGroup(false)
        this.dialogVisiblePublic = true
        this.publicForm = deepClone(row)
        this.$nextTick(() => {
          this.$refs['publicForm'].clearValidate()
        })
      }
    }

  }
}

</script>

<style lang="scss">
  .email-warning {
      width: 764px;
    .warning-wrap {
      width: 100%;
      max-height: 528px;
      overflow-y: auto;
    }

    .warnning-line {
      width:100%;
      color: #E6A23C;
    }
  }

  .table-column-hidden .el-checkbox__input {
    display: none
  }

</style>
